package com.tledu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tledu.config.UploadProperty;
import com.tledu.core.HasUsername;
import com.tledu.core.Result;
import com.tledu.domain.Book;
import com.tledu.service.IBookService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @author cyrus
 */
@RestController
@AllArgsConstructor
@RequestMapping("/book")
public class BookController {

    private final IBookService bookService;

    private final UploadProperty uploadProperty;

    @PostMapping
    public Result<Integer> insert(@RequestBody Book book) {
        // 插入之前，需要做参数校验
        return Result.success(bookService.insert(book));
    }

    // 自定义规则：是admin用户才能修改Book
    @HasUsername(value = "admin")
    @PutMapping
    public Result<Integer> update(@RequestBody Book book) {
        if (book.getId() == null) {
            return Result.error(400, "请传入id的参数");
        }
        return Result.success(bookService.update(book));
    }

    @DeleteMapping
    public Result<Integer> delete(int id) {
        return Result.success(bookService.delete(id));
    }

    @GetMapping("/{id}")
    public Result<Book> selectById(@PathVariable int id) {
        int i = 1 / 0;
        return Result.success(bookService.selectById(id));
    }

    /**
     * 根据 type精准匹配，根据name模糊匹配
     *
     * @param book 查询条件
     * @return 匹配的列表
     */
    @PostMapping("/list")
    public Result<List<Book>> selectList(@RequestBody Book book) {
        return Result.success(bookService.selectList(book));
    }

    @PostMapping("/page")
    public Result<PageInfo<Book>> page(@RequestBody Book book, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Book> books = bookService.selectList(book);
        PageInfo<Book> pageInfo = new PageInfo<>(books);
        return Result.success(pageInfo);
    }

    @PostMapping("/upload")
    public Result<String> update(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        // 先做格式的校验
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        List<String> supportSuffix = Arrays.asList(".png", ".jpg");
        if (!supportSuffix.contains(suffix.toLowerCase())) {
            return Result.error(500, "只支持png和jpg格式");
        }
        // 需要把文件保存到本地
//        try (
//                InputStream inputStream = file.getInputStream();
//                BufferedInputStream bis = new BufferedInputStream(inputStream);
//                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\02授课留档\\java34期\\java34期课堂案例\\java34\\profile\\" + file.getOriginalFilename()))
//        ) {
//            byte[] buffer = new byte[1024];
//            int len = 0;
//            while ((len = bis.read(buffer)) != -1) {
//                bos.write(buffer, 0, len);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//            return Result.error(500, "文件上传异常，请联系管理员");
//        }
        try {
            file.transferTo(new File(uploadProperty.getLocalPath() + file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(500, "文件上传异常，请联系管理员");
        }
        return Result.success(file.getOriginalFilename());
    }

    @PostMapping("/uploads")
    public Result<String> updates(MultipartFile[] files) {
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            // 先做格式的校验
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            List<String> supportSuffix = Arrays.asList(".png", ".jpg");
            if (!supportSuffix.contains(suffix.toLowerCase())) {
                return Result.error(500, "只支持png和jpg格式");
            }
            try {
                file.transferTo(new File(uploadProperty.getLocalPath() + file.getOriginalFilename()));
            } catch (IOException e) {
                e.printStackTrace();
                return Result.error(500, "文件上传异常，请联系管理员");
            }
        }

        return Result.success("上传成功");
    }
}
